class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.hasFilterValue = true;
    }
    GetFilterValue() {
        return this.dataId;
    }
    // 得到角色数据
    GetEntityData() {
        let item = {};
        item['workFlowId'] = $("#WorkFlowId").val();
        item['workFlowNo'] = $.trim($("#WorkFlowNo").val());        // 流程编号
        item['workFlowName'] = $.trim($("#WorkFlowName").val());    // 流程名称
        item['taskUrl'] = $.trim($("#TaskUrl").val());              // 业务url
        item['description'] = formatNullInputValue($.trim($("#Description").val()));  // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());

        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#WorkFlowId").val(item.workFlowId);
        $("#WorkFlowNo").val(item.workFlowNo);
        $("#WorkFlowName").val(item.workFlowName);
        $("#TaskUrl").val(item.taskUrl);
        $("#Description").val(item.description);

        // 显示明细数据
        _InstancePageLines.BuildDataTable(data.NodeList);
    }
    Save() {
        super.Save(function (data, $self) {
            if (data > 0) {
                if (parseInt($self.pageStatus) === 1) {
                    $self.dataId = data;
                    $("#WorkFlowId").val(data);   // 设置刚才插入的记录ID
                    $("#panelSlave").show();
                    $self.pageStatus = 2;
                }
            }
        });
    }
    New() {
        super.New();
        // 默认设置一些值
        $('#WorkFlowId').val("0");
        $('#tabData01 tbody').empty();
        $("#panelSlave").hide();
        this.dataId = 0;
        this.rows = 0;
        //自适应高度
        _InstancePageLines.AutoAdjustTableHeightForLines();
        $("#WorkFlowNo").focus();
    }
    Expand() {
        super.Expand(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
    /* 折叠 */
    Collapse() {
        super.Collapse(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
}

class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.$input = null;
    }
    BuildDataTable(result) {
        $('#tabData01 tbody').empty();
        // 得到数据列表
        if (result === null || result.length === 0) {
            this.rows = 0;
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
            $('#loading').hide();
            return false;
        }
        let content_01 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (var i = 0; i < result.length; i++) {
            content_01 += '<tr _mash_id="' + result[i].nodeId + '">';
            content_01 += '<td style="padding-left:6px;"><label class="btn" for="R-' + result[i].nodeId + '"><input id="R-' + result[i].nodeId + '" name="_check_row" type="checkbox" onclick="_InstancePageLines.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + result[i].nodeId + '"/><i></i><span></span></label></td>';
            // 删除权限判断
            if ($("#ActionAcl_4").length === 0 || parseInt($("#ActionAcl_4").val() === 0)) {
                content_01 += '<td></td>';
            } else {
                content_01 += '<td class="column__action"><span title="删除" class="trash" onclick="_InstancePageLines.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            }
            content_01 += '<td class="edited-cell">' + result[i].nodeOrder + '</td>';
            content_01 += '<td class="edited-cell">' + result[i].nodeName + '</td>';
            let _tmp = '<label class="forcheck" style="top:9px; left:30px;">' +
                    '    <span></span>' +
                    '    <input type="radio" name="NodeType" class="workload" value="' + result[i].nodeType + '" ' + (parseInt(result[i].nodeType) === 1 ? 'checked' : '') + '/>' +
                    '    <div class="off-radio"></div>' +
                    '    <div class="on-radio"></div>' +
                    '</label>';
            content_01 += '<td>' + _tmp + '</td>';
            content_01 += '<td _mash_task_user_groupid="' + result[i].taskUserGroupId + '" class="edited-cell">' + result[i].taskUserGroupName + '</td>';
            if (result[i].nodeRuleFlag === false) {
                content_01 += '<td><label style="margin-left:30px;" class="btn" for="c-' + result[i].nodeId + '-rule"><input id="c-' + result[i].nodeId + '-rule" name="_select_row_rule" type="checkbox" onclick="_InstancePageLines.DoCheckNodeRuleFlag($(this));" /><i></i><span></span></label></td>';
            } else {
                content_01 += '<td><label style="margin-left:30px;" class="btn" for="c-' + result[i].nodeId + '-rule"><input id="c-' + result[i].nodeId + '-rule" name="_select_row_rule" type="checkbox" checked="checked" onclick="_InstancePageLines.DoCheckNodeRuleFlag($(this));" /><i></i><span></span></label></td>';
            }
            if (parseInt(result[i].isAllPassFlag) === 0) {
                content_01 += '<td><label style="margin-left:30px;" class="btn" for="c-' + result[i].nodeId + '-flag"><input id="c-' + result[i].nodeId + '-flag" name="_select_row_flag" type="checkbox" onclick="_InstancePageLines.DoCheckAllPassFlag($(this));" /><i></i><span></span></label></td>';
            } else {
                content_01 += '<td><label style="margin-left:30px;" class="btn" for="c-' + result[i].nodeId + '-flag"><input id="c-' + result[i].nodeId + '-flag" name="_select_row_flag" type="checkbox" checked="checked" onclick="_InstancePageLines.DoCheckAllPassFlag($(this));" /><i></i><span></span></label></td>';
            }
            content_01 += '<td class="edited-cell">' + result[i].description + '</td>';
            content_01 += '</tr>';

            $('#tabData01 tbody').append(content_01);
            content_01 = '';
        }
        setOneTableRowColor("tabData01");

        let id = "cell__field";
        let name = "_cell__field";
        let _this = this;
        $('#tabData01 tbody tr').find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                case 4:
                    break;
                case 5:
                    OnCellPopupEditEvent($(this), id, name, ($input) => {
                        _this.DoChoiceTaskUserGroup($input);
                    });
                    break;
                default:
                    OnCellClickEvent($(this), id, name, 0);
                    break;
            }
        });

        $("input[name='NodeType']").change(function () {
            $("input[type=radio][name='NodeType'][value=1]").parent().parent().addClass('dirty');
            $("input[type=radio][name='NodeType'][value=1]").val(0);
            $(this).val(1);
            $(this).parent().parent().addClass('dirty');
        });

        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();
        $('#loading').hide();
    }
    // 得到流程步骤明细
    GetLinesData() {
        let jsonInsert = [];
        let jsonUpdate = [];
        let itemResult = {};
        let jsonResult = [];
        // 得到修改过数据
        $('#tabData01 tbody').find("tr").each(function () {
            if ($(this).find("td.dirty").length) {
                let item = {};
                let $row = $(this);

                item['nodeId'] = $row.attr('_mash_id');
                item['workFlowId'] = $("#WorkFlowId").val();
                item['workFlowName'] = $("#WorkFlowName").val();
                item['nodeOrder'] = $.trim($row.find('td').eq(2).text());
                item['nodeName'] = $.trim($row.find('td').eq(3).text());
                item['nodeType'] = $row.find('td').eq(4).find("input[type=radio]").eq(0).val();            // 是否是最终步骤
                item['taskUserGroupId'] = $.trim($row.find('td').eq(5).attr("_mash_task_user_groupid"));
                item['nodeRuleFlag'] = $row.find('td').eq(6).find("input").eq(0).is(":checked") ? true : false;  // 节点操作规则
                item['isAllPassFlag'] = $row.find('td').eq(7).find("input").eq(0).is(":checked") ? 1 : 0;        // 是否该节点的审批人必须全部审批通过标记
                item['description'] = $.trim($row.find('td').eq(8).text());
                item['createdBy'] = parent.$("#UserId").val();
                item['updatedBy'] = parent.$("#UserId").val();

                if (parseInt($row.attr("_mash_id")) === 0) {
                    jsonInsert.push(item);
                } else {
                    jsonUpdate.push(item);
                }
            }
        });
        itemResult['insertList'] = jsonInsert;
        itemResult['updateList'] = jsonUpdate;
        jsonResult.push(itemResult);
        //return JSON.stringify(itemResult);
        return itemResult;
    }
    // 保存
    SaveLines() {
        //step 1、进行页面验证，失败则返回
        let success_01 = CheckGridInput();
        if (!success_01)
            return;

        //step 2、执行处理
        if (this.GetLinesData().insertList.length > 0 || this.GetLinesData().updateList.length > 0) {
            super.DoAjax(this.GetLinesData(), "/workflow/workflow_def/lines/batch/save.html", function (data, $self) {
                if (data.LinesList !== undefined) {
                    $self.BuildDataTable(data.LinesList);
                    ShowSuccessMessagePanel("保存成功。");
                }
            });
        }
    }
    DeleteLines($self) {
        let params = {};
        params['nodeId'] = $self.parent().parent().attr("_mash_id");
        params['nodeName'] = $self.parent().parent().find("td").eq(3).text();
        params['workFlowId'] = $("#WorkFlowId").val();
        params['workFlowName'] = $("#WorkFlowName").val();
        params['deletedBy'] = $("#UserId").val();

        super.DeleteLines(params, "/workflow/workflow_def/lines/delete.html", function (data, _this) {
            if (data.LinesList !== undefined) {
                // 刷新明细
                _this.BuildDataTable(data.LinesList);
            }
            ShowSuccessMessagePanel('删除成功。');
        });
    }
    // 批量删除
    BatchDeleteLines() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请先选择要删除的数据。");
            return false;
        }
        showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除所选数据吗？', () => {
            super.DoAjax(this.GetCheckedLinesData(), "/workflow/workflow_def/lines/batch/delete.html", function (data, $self) {
                $self.BuildDataTable(data.LinesList);
                $("#CheckAll").prop("checked", false);
                ShowSuccessMessagePanel('删除成功。');
            });
        });
    }
    // 得到选择的数据
    GetCheckedLinesData() {
        let _result = [];
        $('#tabData01 tbody').find("tr").each(function () {
            if ($(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row']").is(":checked") === true) {
                let instance = {};
                instance['nodeId'] = $(this).attr("_mash_id");
                instance['nodeName'] = $.trim($(this).find("td").eq(3).text());
                instance['workFlowId'] = $.trim($("#WorkFlowId").val());
                instance['workFlowName'] = $.trim($("#WorkFlowName").val());
                instance['updatedBy'] = $.trim($("#UserId").val());
                instance['deletedBy'] = $.trim($("#UserId").val());
                _result.push(instance);
            }
        });
        return _result;
    }
    InsertNewLines() {
        let randomId = Math.round(new Date().getTime() / 1000);
        let _tmp = '<label class="forcheck" style="top:10px; left:30px;">' +
                '    <span></span>' +
                '    <input type="radio" name="NodeType" class="workload" value="0" />' +
                '    <div class="off-radio"></div>' +
                '    <div class="on-radio"></div>' +
                '</label>';
        let $newLine = $('<tr class="newLine" _mash_id="0" >' +
                '    <td></td>' +
                '    <td style="text-align:center;"><span title="删除" class="trash" onclick="_InstancePageLines.RemoveNewLine($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td>' + _tmp + '</td>' +
                '    <td _mash_task_user_groupid="" class="edited-cell"></td>' +
                '    <td class="edited-cell"><label style="margin-left:30px;" class="btn" for="c-' + randomId + '_rule"><input id="c-' + randomId + '_rule" name="_select_row" type="checkbox" onclick="linesHandler.DoCheckNodeRuleFlag($(this));" /><i></i><span></span></label></td>' +
                '    <td class="edited-cell"><label style="margin-left:30px;" class="btn" for="c-' + randomId + '_flag"><input id="c-' + randomId + '_flag" name="_select_row" type="checkbox" onclick="linesHandler.DoCheckAllPassFlag($(this));" /><i></i><span></span></label></td>' +
                '    <td class="edited-cell"></td>' +
                '</tr>');
        $('#tabData01 tbody').prepend($newLine);   // 加在前面
        this._rows = this._rows + 1;
        this.AutoAdjustTableHeightForLines();
        setOneTableRowColor("tabData01");

        $("input[name='NodeType']").change(function () {
            $("input[type=radio][name='NodeType'][value=1]").parent().parent().addClass('dirty');
            $("input[type=radio][name='NodeType'][value=1]").val(0);
            $(this).val(1);
            $(this).parent().parent().addClass('dirty');
        });

        let id = "cell__field";
        let name = "_cell__field";
        let _this = this;
        $newLine.find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                case 4:
                    break;
                case 5:
                    OnCellPopupEditEvent($(this), id, name, ($input) => {
                        _this.DoChoiceTaskUserGroup($input);
                    });
                    break;
                default:
                    OnCellClickEvent($(this), id, name, 0);
                    break;
            }
        });

        return $newLine;
    }
    RemoveNewLine($self) {
        showModal(350, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？', () => {
            $self.parent().parent().remove();
            this._rows = this._rows - 1;
            // 自适应高度设置
            this.AutoAdjustTableHeightForLines();
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, function ($row, index) {
            // 设置删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
        }, function ($row, index) {
            // 设置删除按钮有效
            let _event_delete_onclick = '_InstancePageLines.DeleteLines($(this))';
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_delete_onclick);
        });
    }
    DoCheckAllPassFlag($self) {
        $self.parent().parent().addClass("dirty");
    }
    DoCheckNodeRuleFlag($self) {
        $self.parent().parent().addClass("dirty");
    }
    DoChoiceTaskUserGroup($input) {
        this.$input = $input;
        let _choice = new CommonChoice();
        _choice.DoChoiceTaskUserGroup(0, "选择流程任务操作者", (data) => {
            if (data === false) {
                this.$input.focus();
            } else {
                this.$input.parent().attr("_mash_task_user_groupid", parent.arrChoice[0][0]);
                this.$input.val(parent.arrChoice[0][2]);
                this.$input.focus();
            }
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = $("#divD1").offset().top;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        let _rc = Math.floor((h - _tabTop) / 25);
        let _dh = _rc * 25;
        let _rowH = this._rows * 25; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD1").css({"max-height": _dh, height: _dh});
    }
}

var _InstancePageHeader = null;
var _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#WorkFlowId").val();

    let workflow_def_list_result = $.cookie("workflow_def_list_result") === undefined ? "" : $.cookie("workflow_def_list_result");
    let _pageListData = [];
    if (workflow_def_list_result !== "") {
        _pageListData = workflow_def_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/workflow/workflow_def/list.html",
            "/workflow/workflow_def/fetchByKey.html",
            "/workflow/workflow_def/save.html",
            null, null);

    _InstancePageLines = new MyPageLines();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelContent"});

    $("#hPanelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-up")) {
            _InstancePageHeader.Collapse();
        } else {
            _InstancePageHeader.Expand();
        }
    });

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    if (_InstancePageLines !== null)
        _InstancePageLines.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _WorkFlowNo: "required",
            _WorkFlowName: "required",
            _TaskUrl: "required"
        },
        messages: {
            _WorkFlowNo: "请填写流程编号。",
            _WorkFlowName: "请填写流程名称。",
            _TaskUrl: "请填写业务URL。"

        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
//验证输入
function CheckGridInput() {
    $('#tabData01 tbody').find("tr").each(function () {
        var $row = $(this);
        var _OrderNo = $.trim($(this).find('td').eq(2).text());         // 序号
        var _NodeName = $.trim($(this).find('td').eq(3).text());        // 步骤名
        var _TaskUser = $.trim($(this).find('td').eq(5).text());        // 任务操作者

        if (_OrderNo === '') {
            GridCheckErrHandle($row, 2, '请输流程步骤顺序。');
        } else {
            GridCheckSuccessHandle($row, 2);
        }

        if (_NodeName === '') {
            GridCheckErrHandle($row, 3, '请输入流程步骤名。');
        } else {
            GridCheckSuccessHandle($row, 3);
        }

        if (_TaskUser === '') {
            GridCheckErrHandle($row, 5, '请输入任务操作者。');
        } else {
            GridCheckSuccessHandle($row, 5);
        }
    });
    if ($('#tabData01 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}